from app.libs.email import send_email
from app.models.gift import Gift
from app.models.wish import Wish
from app.view_models.wish import WishViewModel
from . import web
from flask_login import current_user, login_required
from flask import flash, redirect, url_for, render_template
from app import db, limit


@web.route('/my/wish')
@login_required
def my_wish():
    wishs = Wish.get_user_wishs(current_user.id)
    isbn_list = [wish.isbn for wish in wishs]
    gift_list = Wish.get_gift_counts(isbn_list)
    view_model = WishViewModel(wishs, gift_list)
    return render_template('my_wish.html', wishes=view_model.wishs)


@web.route('/wish/book/<isbn>')
@login_required
def save_to_wish(isbn):
    if current_user.can_save_to_list(isbn):
        with db.auto_commit():
            wish = Wish()
            wish.isbn = isbn
            wish.uid = current_user.id
            db.session.add(wish)

    else:
        flash('书籍存在心愿清单,或已赠送,请不要重复添加.')
    return redirect(url_for('web.book_detail', isbn=isbn))


@web.route('/satisfy/wish/<int:wid>')
@login_required
def satisfy_wish(wid):
    wish = Wish.query.get_or_404(wid)
    # 查询需要赠送的礼物,当前用户是否有,是否赠送过.
    gift = Gift.query.filter_by(uid=current_user.id, isbn=wish.isbn, launched=False).first()
    if not gift:
        flash('请先赠送这本书')
    else:
        send_email(wish.user.email, '%s赠送您一本书'%current_user.nickname,
                   'email/satisify_wish.html', wish=wish, gift=gift)
        flash('已向想要用户成功发送一封邮件')
    return redirect(url_for('web.book_detail', isbn=wish.isbn))


@web.route('/wish/book/<isbn>/redraw')
@login_required
def redraw_from_wish(isbn):
    wish = Wish.query.filter_by(isbn=isbn, uid=current_user.id, launched=False).first_or_404()
    with db.auto_commit():
        wish.delete()
    return redirect(url_for('web.my_wish'))